package com.zg.common.core.validation;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 字符串取值范围校验
 * @author Zxb
 */
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {StrRange.Validator.class})
public @interface StrRange {

    String message() default "不在取值范围";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String[] arr() default {};

    class Validator implements ConstraintValidator<StrRange, String> {
        private final Set<String> set = new HashSet<>();

        @Override
        public void initialize(StrRange constraintAnnotation) {
            String[] arr = constraintAnnotation.arr();
            Collections.addAll(set, arr);
        }

        @Override
        public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
            return set.contains(str);
        }

    }
}
